<script setup>
import { computed, ref, watch } from 'vue';
import { reasonList, using } from '../common.js';
import { picState } from '../api/use-task';
import { delLayer } from '../api/use-layer-common.js';
import { judge } from '../api/use-judge.js';

const RejFormState = () => ({
  rejectReason: reasonList.value[0],
  remark: '',
});

const props = defineProps(['visible', 'action', 'all']);
const emit = defineEmits(['update:visible', 'judge']);

const title = computed(() => `${ props.all ? '整包' : '' }${ props.action }`);
const sending = ref(false);

const visible = ref(props.visible);
watch(() => visible.value, newVal => emit('update:visible', newVal));

const formElem = ref();

const FormState = k => ({
  '批注': () => R.last(picState.value.comments),
  '驳回': RejFormState,
})[k];

const formState = ref(FormState(props.action)());

function handleJudge() {
  const Result = () => ({ [props.all ? 'wholePackagePass' : 'pass']: false });

  sending.value = true;
  judge( Object.assign(Result(), formState.value) )
  .then(() => emit('update:visible', false))
  .finally(() => sending.value = false);
}

function cancel() {
  if ('批注' == props.action) {
    delLayer(formState.value);
    using.value = 'none';
  }

  visible.value = false;
}

function confirm() {
  formElem.value
  .validate()
  .then(
    ({
      '批注': () => {
        emit('update:visible', false);
        using.value = 'none';
      },
      '驳回': handleJudge,
    })[props.action]
  )
  .catch(() => {});
}
</script>

<template>
  <a-modal
    :visible="visible"
    :width="384"
    :title="title"
    :closable="false"
    class="judge-modal">

    <a-form
      ref="formElem"
      layout="vertical"
      :model="formState">
      <a-form-item required label="错误原因" name="rejectReason">
        <a-radio-group v-model:value="formState.rejectReason">
          <template v-for="item in reasonList">
            <a-radio-button :value="item">{{ item }}</a-radio-button>
          </template>
        </a-radio-group>
      </a-form-item>
      
      <a-form-item label="详细描述" name="remark">
        <a-textarea
          v-model:value="formState.remark"
          :auto-size="{ minRows: 3 }"
          placeholder="请输入详细错误原因"
          show-count
          :maxlength="100"
        >
        </a-textarea>
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button @click="() => cancel()">取消</a-button>
      <a-button type="primary" :disabled="sending" @click="() => confirm()">确定</a-button>
    </template>
  </a-modal>
</template>

<style>
.judge-modal .ant-modal-footer { text-align: center; }
</style>
